package com.wn.naturalbiorhythms;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.TreeMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;

import com.wn.naturalbiorhythms.bean.NaturalValue;
import com.wn.naturalbiorhythms.tool.BirthdaySettingsSharePref;
import com.wn.naturalbiorhythms.view.NaturalBiorhythmsView;

/**
 * 人体节律计算器
 * 
 * @author Grant Woo
 * @date 2011年3月24日22:07:54
 * */
public class NaturalBiorhythmsActivity extends Activity implements
		OnTouchListener, OnGestureListener {

	private GestureDetector gestureDetector = null;

	private NaturalBiorhythmsView nbview = null;

	// private DatePicker birthdayPicker = null;
	
	private byte[]showDays = {17,23,28,33};
	private byte[]textSizeList = {18,16,14,12};
	private SimpleDateFormat sdf_yyyy_MM_dd_E = new SimpleDateFormat("yyyy-MM-dd E");
	private String tend_up;
	private String tend_down;
	
	//private TreeMap<Float, NaturalValue> nValueMap = new TreeMap<Float, NaturalValue>();

	//private List<Float>xKeys = new ArrayList<Float>();
	
	private Button btn_back;
	private Button btn_other;
	
	private TextView  tv_calendar;
	private TextView  tv_tend_physical;
	private TextView  tv_tend_emotional;
	private TextView  tv_tend_intellictual;
	private TextView  tv_tend_intuitive;
	private TextView  tv_physical;
	private TextView  tv_emotional;
	private TextView  tv_intellictual;
	private TextView  tv_intuitive;
	private TextView  tv_daysLived;
	
	private TextView  tv_InCycle_physical;
	private TextView  tv_InCycle_emotional;
	private TextView  tv_InCycle_intellictual;
	private TextView  tv_InCycle_intuitive;
	
	private Button btn1_toSomeday;
	private Button btn2_toToday;
	private Button btn3_toBirthday;
	private BirthdaySettingsSharePref bsspref;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		//自定义title
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		
		
		DisplayMetrics display = getResources().getDisplayMetrics();
		if(display.heightPixels >= 960){
			setContentView(R.layout.main_960);
		}else{
			setContentView(R.layout.main);
		}
		
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.activity_title);
		initTitleBar();
		
		gestureDetector = new GestureDetector(this);

		initView();
		initData();
		setListener();
		NaturalBiorhythmsApplication.addActivity(this);
	}

	private void initView() {
		bsspref = BirthdaySettingsSharePref.getInstance(this);
		nbview = (NaturalBiorhythmsView)findViewById(R.id.naturalBiorhythmsView1);
		
		btn1_toSomeday = (Button)findViewById(R.id.button1_toSomeday);
		btn2_toToday = (Button)findViewById(R.id.button2_toToday);
		btn3_toBirthday = (Button)findViewById(R.id.button3_toBirthday);
		
		tv_calendar =(TextView)findViewById(R.id.textView2_calendar);
		
		tv_tend_physical =(TextView)findViewById(R.id.textView2_tend_Physical);
		tv_tend_emotional =(TextView)findViewById(R.id.textView4_tend_Emotional);
		tv_tend_intellictual =(TextView)findViewById(R.id.textView6_tend_Intellictual);
		tv_tend_intuitive =(TextView)findViewById(R.id.textView8_tend_Intuitive);
		
		
		
		tv_physical =(TextView)findViewById(R.id.textView2_physical);
		tv_emotional =(TextView)findViewById(R.id.textView4_emotional);
		tv_intellictual =(TextView)findViewById(R.id.textView6_intellictual);
		tv_intuitive =(TextView)findViewById(R.id.textView8_intuitive);
		tv_daysLived =(TextView)findViewById(R.id.textView10_days_lived);
		
		tv_InCycle_physical =(TextView)findViewById(R.id.textView2_InCyclePhysical);
		tv_InCycle_emotional =(TextView)findViewById(R.id.textView4_InCycleEmotional);
		tv_InCycle_intellictual =(TextView)findViewById(R.id.textView6_InCycleIntellictual);
		tv_InCycle_intuitive =(TextView)findViewById(R.id.textView8_InCycleIntuitive);
	}
	
	private void initData() {
		tend_up = getString(R.string.tend_up);
		tend_down = getString(R.string.tend_down);
	}
	
	private void setListener() {

		nbview.setLongClickable(true);
		nbview.setOnTouchListener(this);
		
		btn1_toSomeday.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				final Calendar taday = Calendar.getInstance();
				int y22 = taday.get(Calendar.YEAR);
				int m22 = taday.get(Calendar.MONTH);
				int d22 = taday.get(Calendar.DAY_OF_MONTH);
				taday.clear();
				taday.set(y22, m22, d22);
				DatePickerDialog setting1 = new DatePickerDialog(NaturalBiorhythmsActivity.this,
						new OnDateSetListener() {
							@Override
							public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
								Calendar cal = Calendar.getInstance();
								cal.clear();
								cal.set(year, monthOfYear, dayOfMonth);
								if (cal.after(taday)) {
									nbview.setStart(cal.getTimeInMillis()- taday.getTimeInMillis(), 1);
								} else {
									nbview.setStart(taday.getTimeInMillis()- cal.getTimeInMillis(), -1);
								}

							}

						}, y22, m22, d22);
				setting1.setTitle(R.string.menu_moveto_setting_datepickerdialog_title);
				setting1.show();
			}
		});
		btn2_toToday.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				final Calendar taday = Calendar.getInstance();
				int y21 = taday.get(Calendar.YEAR);
				int m21 = taday.get(Calendar.MONTH);
				int d21 = taday.get(Calendar.DAY_OF_MONTH);
				taday.clear();
				taday.set(y21, m21, d21);
				nbview.setToday(taday.getTimeInMillis());

			}
		});
		btn3_toBirthday.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				nbview.resetStart();
			}
		});
	}

	private void initTitleBar() {
		btn_back = (Button)findViewById(R.id.button1_back);
		btn_back.setText(R.string.title_bar_btn1_exit);
		btn_back.setBackgroundResource(R.anim.btn_style_exit);
		TextView titleTxt =  (TextView)findViewById(R.id.textView1_title);
		titleTxt.setText(R.string.app_name);
		btn_other = (Button)findViewById(R.id.button2_other);
		btn_other.setText(R.string.title_bar_btn2_other);
		
		btn_back.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		btn_other.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				startActivity(new Intent(NaturalBiorhythmsActivity.this, MoreOpActivity.class));
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		/*menu.add(0, 0, 0, R.string.menu_knowledge_title).setIcon(
				R.drawable.knowledge);
		menu.add(0, 1, 1, R.string.menu_setting_title).setIcon(
				R.drawable.setting);

		SubMenu moveTo = menu.addSubMenu(0, 2, 2, R.string.menu_moveto_title)
				.setIcon(R.drawable.moveto);
		moveTo.add(2, 20, 0, R.string.menu_moveto_birthday_title);
		moveTo.add(2, 21, 1, R.string.menu_moveto_today_title);
		moveTo.add(2, 22, 2, R.string.menu_moveto_setting_title);

		menu.add(0, 3, 3, R.string.menu_helping_title).setIcon(
				R.drawable.helping);
		menu.add(0,4,4,R.string.menu_exit_title).setIcon(
				R.drawable.exit);
		return super.onCreateOptionsMenu(menu);*/
		
		//getMenuInflater().inflate(R.menu.main_menu, menu);
		return true;
	}
	
		
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		final Calendar taday = Calendar.getInstance();
		switch (item.getItemId()) {
		case R.id.item1_menu_knowledge:
			AlertDialog.Builder knowledge = new AlertDialog.Builder(this);
			knowledge.setTitle(R.string.knowledgedialog_title).setMessage(
					R.string.knowledge_msg).setPositiveButton(
					R.string.positivebutton_text, null).show();
			KEYCODE_BACK_PRESS_NUM = 0;
			break;
		case R.id.item2_menu_setting_birthay:
			// AlertDialog.Builder setting = new AlertDialog.Builder(this);
			// birthdayPicker = new DatePicker(this);
			// setting.setTitle("Setting your birthday").
			// setPositiveButton("OK", new DialogInterface.OnClickListener() {
			//						
			// @Override
			// public void onClick(DialogInterface dialog, int which) {
			// Calendar cal = Calendar.getInstance();
			// cal.clear();
			// cal.set(birthdayPicker.getYear(), birthdayPicker.getMonth() ,
			// birthdayPicker.getDayOfMonth());
			// nbview.setBirthday(cal.getTimeInMillis());
			// }
			// }).
			// setNegativeButton("Cancel", null).setView(birthdayPicker).
			// show();
			
			
			
			/*Calendar calendar = Calendar.getInstance();
			DatePickerDialog setting = new DatePickerDialog(this,
					new OnDateSetListener() {
						@Override
						public void onDateSet(DatePicker view, int year,
								int monthOfYear, int dayOfMonth) {
							Calendar cal = Calendar.getInstance();
							cal.clear();
							cal.set(year, monthOfYear, dayOfMonth);
							nbview.setBirthday(cal.getTimeInMillis());
						}

					}, calendar.get(Calendar.YEAR), calendar
							.get(Calendar.MONTH), calendar
							.get(Calendar.DAY_OF_MONTH));
			setting.setTitle(R.string.datepickerdialog_title);
			setting.show();*/
			Intent intent0 = new Intent(NaturalBiorhythmsActivity.this, BirthdaySettingsActivity.class);
			startActivity(intent0);
			KEYCODE_BACK_PRESS_NUM = 0;
			break;
		case R.id.item6_1_menu_setting_showdays:
			nbview.setShowDays(showDays[0],textSizeList[0]);
			KEYCODE_BACK_PRESS_NUM = 0;
			
			break;
		case R.id.item6_2_menu_setting_showdays:
			nbview.setShowDays(showDays[1],textSizeList[1]);
			KEYCODE_BACK_PRESS_NUM = 0;
			
			break;
		case R.id.item6_3_menu_setting_showdays:
			nbview.setShowDays(showDays[2],textSizeList[2]);
			KEYCODE_BACK_PRESS_NUM = 0;
			
			break;
		case R.id.item6_4_menu_setting_showdays:
			nbview.setShowDays(showDays[3],textSizeList[3]);
			KEYCODE_BACK_PRESS_NUM = 0;
			
			break;
		case R.id.item4_menu_helping:
			AlertDialog.Builder help = new AlertDialog.Builder(this);
			help.setTitle(R.string.helpdialog_title).setMessage(
					R.string.helpdialog_msg).setPositiveButton(
					R.string.positivebutton_text, null).show();
			KEYCODE_BACK_PRESS_NUM = 0;
			break;
		case R.id.item3_1_menu_moveto_birthday:
			nbview.resetStart();
			KEYCODE_BACK_PRESS_NUM = 0;
			break;
		case R.id.item3_2_menu_moveto_today:

			int y21 = taday.get(Calendar.YEAR);
			int m21 = taday.get(Calendar.MONTH);
			int d21 = taday.get(Calendar.DAY_OF_MONTH);
			taday.clear();
			taday.set(y21, m21, d21);
			nbview.setToday(taday.getTimeInMillis());
			KEYCODE_BACK_PRESS_NUM = 0;
			break;
		case R.id.item3_3_menu_moveto_setting:

			int y22 = taday.get(Calendar.YEAR);
			int m22 = taday.get(Calendar.MONTH);
			int d22 = taday.get(Calendar.DAY_OF_MONTH);
			taday.clear();
			taday.set(y22, m22, d22);
			DatePickerDialog setting1 = new DatePickerDialog(this,
					new OnDateSetListener() {
						@Override
						public void onDateSet(DatePicker view, int year,
								int monthOfYear, int dayOfMonth) {
							Calendar cal = Calendar.getInstance();
							cal.clear();
							cal.set(year, monthOfYear, dayOfMonth);
							if (cal.after(taday)) {
								nbview.setStart(cal.getTimeInMillis()
										- taday.getTimeInMillis(), 1);
							} else {
								nbview.setStart(taday.getTimeInMillis()
										- cal.getTimeInMillis(), -1);
							}

						}

					}, taday.get(Calendar.YEAR), taday.get(Calendar.MONTH),
					taday.get(Calendar.DAY_OF_MONTH));
			setting1
					.setTitle(R.string.menu_moveto_setting_datepickerdialog_title);
			setting1.show();
			KEYCODE_BACK_PRESS_NUM = 0;
			break;
		case R.id.item5_menu_exit:
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle(R.string.alertdialog_title).
			setMessage(R.string.alertdialog_msg).
			setPositiveButton(R.string.alertdialog_positivebutton_text, new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			}).
			setNegativeButton(R.string.alertdialog_negativebutton_text, null).
			show();
			
			break;
		}

		return super.onContextItemSelected(item);
	}


	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// GestureDetector会根据转入的MotionEvent事件来判断用户进行了哪种操作。
		return gestureDetector.onTouchEvent(event);
	}

	@Override
	public boolean onDown(MotionEvent e) {
		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		Log.i("NaturalBiorhythmsActivity", "onFling");
		return false;
	}
	
	private Float floorKey(List<Float>xKeys,float x){
		if(xKeys.contains(Float.valueOf(x))){
			return Float.valueOf(x);
		}
		for(int i=0;i<xKeys.size()-1;i++){
			
			float kf = xKeys.get(i);
			float kn = xKeys.get(i+1);
			if(kf<x && x<kn){
				return Float.valueOf(kf);
			}
		}
		return xKeys.get(xKeys.size()-1);
	}

	private Float getNextKey(List<Float>xKeys,float x){
		int i = xKeys.indexOf(floorKey(xKeys,x));
		if(i==xKeys.size()-1){
			return xKeys.get(i);
		}
		return xKeys.get(i+1);
	}
	
	private void updateDetail(NaturalValue  nvalue,NaturalValue next_nvalue){
		String tend_physical = "";
		String tend_emotional = "";
		String tend_intellictual = "";
		String tend_intuitive = "";
		
		if(next_nvalue!=null){
			
			tend_physical = tend_down;
			if(next_nvalue.getPhysical()>=nvalue.getPhysical()){
				tend_physical = tend_up;
			}
			
			tend_emotional = tend_down;
			if(next_nvalue.getEmotional()>=nvalue.getEmotional()){
				tend_emotional = tend_up;
			}
			
			tend_intellictual = tend_down;
			if(next_nvalue.getIntellictual()>=nvalue.getIntellictual()){
				tend_intellictual = tend_up;
			}
			
			tend_intuitive = tend_down;
			if(next_nvalue.getIntuitive()>=nvalue.getIntuitive()){
				tend_intuitive = tend_up;
			}
		}
		
		tv_calendar.setText(sdf_yyyy_MM_dd_E.format(nvalue.getCalendar().getTime()));
		tv_tend_physical.setText(tend_physical);
		tv_tend_emotional.setText(tend_emotional);
		tv_tend_intellictual.setText(tend_intellictual);
		tv_tend_intuitive.setText(tend_intuitive);
		
		tv_physical.setText(nvalue.getPhysical()+"");
		tv_emotional.setText(nvalue.getEmotional()+"");
		tv_intellictual.setText(nvalue.getIntellictual()+"");
		tv_intuitive.setText(nvalue.getIntuitive()+"");
		tv_daysLived.setText(nvalue.getDayLived()+"");
		
		
		
		//体力
		byte tp = nvalue.getTypeInCyclePhysical();
		if(tp == 0){
			tv_InCycle_physical.setText(R.string.DayInCycle_Cycle_text);
		}else if(tp == 1){
			tv_InCycle_physical.setText(String.format(getString(R.string.DayInCycle_Climax_text), nvalue.getDayInCyclePhysical()));
		}else if(tp == 2){
			tv_InCycle_physical.setText(R.string.DayInCycle_Critical_text);
		}else{
			tv_InCycle_physical.setText(String.format(getString(R.string.DayInCycle_Lowtide_text), nvalue.getDayInCyclePhysical()));
		}
		
		//情绪
		byte te = nvalue.getTypeInCycleEmotional();
		if(te == 0){
			tv_InCycle_emotional.setText(R.string.DayInCycle_Cycle_text);
		}else if(te == 1){
			tv_InCycle_emotional.setText(String.format(getString(R.string.DayInCycle_Climax_text), nvalue.getDayInCycleEmotional()));
		}else if(te == 2){
			tv_InCycle_emotional.setText(R.string.DayInCycle_Critical_text);
		}else{
			tv_InCycle_emotional.setText(String.format(getString(R.string.DayInCycle_Lowtide_text), nvalue.getDayInCycleEmotional()));
		}
		
		//智力
		byte ti = nvalue.getTypeInCycleIntellictual();
		if(ti == 0){
			tv_InCycle_intellictual.setText(R.string.DayInCycle_Cycle_text);
		}else if(ti == 1){
			tv_InCycle_intellictual.setText(String.format(getString(R.string.DayInCycle_Climax_text), nvalue.getDayInCycleIntellictual()));
		}else if(ti == 2){
			tv_InCycle_intellictual.setText(R.string.DayInCycle_Critical_text);
		}else{
			tv_InCycle_intellictual.setText(String.format(getString(R.string.DayInCycle_Lowtide_text), nvalue.getDayInCycleIntellictual()));
		}
		
		//直觉
		byte tn = nvalue.getTypeInCycleIntuitive();
		if(tn == 0){
			tv_InCycle_intuitive.setText(R.string.DayInCycle_Cycle_text);
		}else if(tn == 1){
			tv_InCycle_intuitive.setText(String.format(getString(R.string.DayInCycle_Climax_text), nvalue.getDayInCycleIntuitive()));
		}else if(tn == 2){
			tv_InCycle_intuitive.setText(R.string.DayInCycle_Critical_text);
		}else{
			tv_InCycle_intuitive.setText(String.format(getString(R.string.DayInCycle_Lowtide_text), nvalue.getDayInCycleIntuitive()));
		}
	}
	
	@Override
	public void onLongPress(MotionEvent e) {
		/*TreeMap<Float, NaturalValue> nValueMap = nbview.getnValueMap();
		List<Float>xKeys = nbview.getxKeys();
		NaturalValue  nvalue= nValueMap.get(floorKey(xKeys,e.getX()));
	    NaturalValue next_nvalue = nValueMap.get(getNextKey(xKeys,e.getX()));
	    updateDetail(nvalue, next_nvalue);*/
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// 用户按下屏幕并拖动，
		// distanceX > 0 手势向左；distanceX < 0 手势向右
		// distanceY > 0 手势向上；distanceX < 0 手势向下
		if(e1.getY()>nbview.getY_bottom() || e2.getY()>nbview.getY_bottom()){
			return true;
		}
		if (distanceX > 20) {
			nbview.setStart(2, 1);
		} else if (distanceX < -20) {
			nbview.setStart(2, -1);
		}
		KEYCODE_BACK_PRESS_NUM = 0;
		return true;
	}

	@Override
	public void onShowPress(MotionEvent e) {
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		Log.i("NaturalBiorhythmsActivity", "onSingleTapUp");
		
		if(e.getY()>nbview.getY_bottom() || e.getY()<nbview.getY_top()){
			return true;
		}
		
		if(e.getX()>nbview.getX_right() || e.getX()<nbview.getX_left()){
			return true;
		}
		
		TreeMap<Float, NaturalValue> nValueMap = nbview.getnValueMap();
		List<Float>xKeys = nbview.getxKeys();
		NaturalValue  nvalue= nValueMap.get(floorKey(xKeys,e.getX()));
	    NaturalValue next_nvalue = nValueMap.get(getNextKey(xKeys,e.getX()));
	    updateDetail(nvalue, next_nvalue);
		return true;
	}
	
	private byte KEYCODE_BACK_PRESS_NUM = 0;
	private long KEYCODE_BACK_PRESS_LastTime = System.currentTimeMillis();
	private Toast showToast;
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(KEYCODE_BACK_PRESS_NUM > 0 || (System.currentTimeMillis() - KEYCODE_BACK_PRESS_LastTime) < 3000){
			finish();
			return true;
		}
		if(event.getKeyCode() == KeyEvent.KEYCODE_BACK){
			showToast = Toast.makeText(this, R.string.exit_msg, Toast.LENGTH_LONG);
			showToast.show();
			KEYCODE_BACK_PRESS_NUM++;
			KEYCODE_BACK_PRESS_LastTime = System.currentTimeMillis();
		}
		return false;
	}

	
	@Override
	protected void onResume() {
		if(bsspref.birthdayIsChanged((byte)0)){
			nbview.setBirthday();
			nbview.invalidate();
		}
		
		super.onResume();
	}
	
	@Override
	protected void onDestroy() {
		if(showToast != null){
			showToast.cancel();
		}
		super.onDestroy();
	}
}